from VizSpread.appengine.models import Dataset, Contact

from google.appengine.ext import db
from google.appengine.api.users import User

class TestDatasetModel():

	def test_creation(self):
		name = "Test2"
		dataCentre = "140 Bond Street, London, UK"
		dataCSV = "bla"
		owner = User(email="test2@foo.com")
	  
		dataset = Dataset(name=name, dataCentre=dataCentre, dataCSV=dataCSV, owner=owner)
		dataset.put()

		fetched_dataset = Dataset.all().filter('name =', name).fetch(1)[0]
		assert fetched_dataset.name == name
		assert fetched_dataset.dataCentre == dataCentre
		assert fetched_dataset.owner == owner

class TestContactModel():

	def setUp(self):
		owner = User(email="test2@foo.com")
		
		dataSetname1 = "Test3"
		dataset1 = Dataset(name=dataSetname1, owner=owner)
		dataset1.put()
		self.dataset1 = dataset1

		dataSetname2 = "Test4"
		dataset2 = Dataset(name=dataSetname2, owner=owner)
		dataset2.put()
		self.dataset2 = dataset2
		
	def test_creation(self):

		contact_name = "John Smith"
		contact_email = "test4@foo.com"
		contact_address = "23 New Church Road, Brighton, East Sussex, UK"

		contact = Contact(set=self.dataset1, name=contact_name, email=contact_email, address=contact_address)
		contact.put()

		results = db.GqlQuery("SELECT * FROM Contact WHERE set = :1", self.dataset1)
		fetched_contact = results[0]

		assert fetched_contact.name == contact_name
		assert fetched_contact.email == contact_email
		assert fetched_contact.address == contact_address
		
	def test_contact_dataset_relation(self):

		contact_address1 = "23 New Church Road, Brighton, East Sussex, UK"
		contact1 = Contact(set=self.dataset1, address=contact_address1)
		contact1.put()

		contact_address2 = "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"
		contact2 = Contact(set=self.dataset2, address=contact_address2)
		contact2.put()

		results = db.GqlQuery("SELECT * FROM Contact WHERE set = :1", self.dataset1)
		
		try:
			fetched_contact = results[0]
			assert fetched_contact.address == contact_address1
		except IndexError:
			assert False
		
		try:
			fetched_contact = results[1]
			assert False # This should raise an eror because there should be only one result
		except IndexError:
			assert True # This is what we want to happen		
